package com.goldmantis.alitrip.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldmantis.alitrip.common.BaseService;
import com.goldmantis.alitrip.mapper.SysRoleMapper;
import com.goldmantis.alitrip.pojo.SysRole;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author:Shmily
 * @Description:
 * @Date:Create in 9:46 2018/2/11
 */
@Service
public class SysRoleService extends BaseService<SysRole> {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    public PageInfo<SysRole> select(SysRole t, Integer offset, Integer limit){

        if(limit==null){
            limit=Integer.MAX_VALUE;
        }

        if(StringUtils.isEmpty(t.getRolename())){
            t.setRolename(null);
        }
        if(StringUtils.isEmpty(t.getCategory())){
            t.setCategory(null);
        }

        PageHelper.startPage(offset,limit);
        List<SysRole> sysRoles = this.sysRoleMapper.getCustom(t);
        return new PageInfo(sysRoles);
    }

    public List<SysRole> selectBySystemId(Long systemId) {
        SysRole sysRole=new SysRole();
        sysRole.setSystemid(systemId);
        return this.select(sysRole);
    }


    /**
     * 判断用户Code是否存在
     * @param sysRole
     * @return
     */
    public SysRole codeExist(SysRole sysRole) {

        Example example=new Example(SysRole.class);
        Example.Criteria criteria = example.createCriteria();

        if(StringUtils.isNotBlank(sysRole.getCode())){
            criteria.andEqualTo("code",sysRole.getCode());
        }
        if(sysRole.getRoleid()!=null&&sysRole.getRoleid()!=0){
            criteria.andNotEqualTo("roleid",sysRole.getRoleid());
        }
        List<SysRole> selected = this.sysRoleMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(selected)){
            return selected.get(0);
        }
        return null;
    }

    /**
     * 判断角色名称是否存在
     * @param sysRole
     * @return
     */
    public SysRole roleNameExist(SysRole sysRole) {

        Example example=new Example(SysRole.class);
        Example.Criteria criteria = example.createCriteria();

        if(StringUtils.isNotBlank(sysRole.getCode())){
            criteria.andEqualTo("rolename",sysRole.getRolename());
        }
        if(sysRole.getRoleid()!=null&&sysRole.getRoleid()!=0){
            criteria.andNotEqualTo("roleid",sysRole.getRoleid());
        }
        List<SysRole> selected = this.sysRoleMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(selected)){
            return selected.get(0);
        }
        return null;
    }
}
